package ui
{
	import Base.Loader.SWFLoader;
	import Base.Net.NetSocket;
	
	import Common.ActionManager;
	import Common.GameAction;
	import Common.GameDefine;
	import Common.GameNetEvent;
	import Common.GameNetManager;
	import Common.MapDirection;
	import Common.RenderManager;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	
	import logic.GameCreatureData;
	import logic.GamePetData;

	public class PetInfoUIHandler extends uiBase
	{
		public var index:int = 0;
		public var pet:GamePet = null;
		public var imgSprite:Sprite;
		private var actionBmpData:Object = null;
		
		private var nameMcMovie:uiMovie;
		private var skillMcMovie:uiMovie;
		private var nameMc:MovieClip;
		private var skillMc:MovieClip;
		
		public function PetInfoUIHandler()
		{
			path = "petInfo.swf";
			name = "PetInfoUI";
		}
		
		
		public override function onInit( loader:SWFLoader ):void
		{
			super.onInit( loader );
			
			var clas:Class = loader.getClass( "PetChangeNameUI" );
			nameMc = new clas();
			nameMcMovie = new uiMovie();
			nameMcMovie.init( nameMc );
			uiMc.addChild( nameMc );
			nameMc.visible = false;
			
			clas = loader.getClass( "PetSkillUI" );
			skillMc = new clas();
			skillMcMovie = new uiMovie();
			skillMcMovie.init( skillMc );
			GameUIManager.instance.addLevel1UI( skillMc );
			skillMc.visible = false;
			skillMc.backBtn.addEventListener( MouseEvent.CLICK , onSkillBack );
			
			nameMc.okBtn.addEventListener( MouseEvent.CLICK , onNameOk );
			nameMc.nameText.restrict = "A-Za-z0-9\u4e00-\u9fa5";
			
			uiMc.preBtn.addEventListener( MouseEvent.CLICK , onPre );
			uiMc.nextBtn.addEventListener( MouseEvent.CLICK , onNext );
			uiMc.returnBtn.addEventListener( MouseEvent.CLICK , onReturn );
			uiMc.changeNameBtn.addEventListener( MouseEvent.CLICK , onName );
			uiMc.skillBtn.addEventListener( MouseEvent.CLICK , onSkill );
			uiMc.photoBtn.addEventListener( MouseEvent.CLICK , onPhoto );
			
			imgSprite = new Sprite();
			imgSprite.addEventListener( MouseEvent.CLICK , onImgClick );
			uiMc.petImg.addChild( imgSprite );
			
			actionBmpData = ActionManager.instance.bmpData;
			
			show( index );
			
			resize();
		}
		
		
		public override function resize():void
		{
			if ( skillMc )
			{
				uiMc.x = uiMc.px + 15;
				uiMc.y = RenderManager.instance.stageHeight * 0.1 + uiMc.py;
				
				skillMc.x = uiMc.px + 15;
				skillMc.y = RenderManager.instance.stageHeight * 0.1 + uiMc.py;
			}
		}
		
		public function visibleName( b:Boolean ):void
		{
			if ( b )
			{
				nameMcMovie.startTimer();
			}
			else
			{
				nameMc.visible = false;
				RenderManager.instance.stage.focus = nameMc.nameText;
			}
		}
		
		public function visibleSkill( b:Boolean ):void
		{
			if ( !skillMc )
			{
				return;
			}
			
			if ( b )
			{
				skillMcMovie.startTimer();
			}
			else
			{
				skillMc.visible = false;
			}
		}
		
		public function onPre( e:MouseEvent ):void
		{
			if ( index == 0 )
			{
				return;
			}
			
			index--;
			
			show( index );
		}
		
		public function onNext( e:MouseEvent ):void
		{
			if ( index == GameManager.instance.MainPlayer.petArray.length - 1 )
			{
				return;
			}
			
			index++;
			
			show( index );
		}
		
		public function onReturn( e:MouseEvent ):void
		{
			this.visible( false );
			PetUIHandler.instance.visible( true );
		}
		
		public function onName( e:MouseEvent ):void
		{
			visibleName( true );
		}
		
		public function onSkill( e:MouseEvent ):void
		{
			this.visible( false );
			visibleSkill( true );
		}
		
		public function onPhoto( e:MouseEvent ):void
		{
			var data:GameCreatureData = GameManager.instance.MainPlayer.petArray[index].data;
			var petData:GamePetData = GameManager.instance.MainPlayer.petArray[index].petData;
			
			var sa:SharedObject = SharedObject.getLocal( "foxSA" );
			sa.data[ petData.id ] = { n:petData.name , p:petData.photo , g:data.Index , l:data.Level , h:data.HP , s:data.Strength , t:data.Toughness , d:data.Dexterity };
			
			saveSharedObject( sa );
		}
		
		public function saveSharedObject( obj:SharedObject ):void
		{
			try 
			{
				var flushResult:String = obj.flush( );
				// If the flush operation is pending, add an event handler for
				// netStatus to determine if the user grants or denies access.
				// Otherwise, just check the result.
				if ( flushResult == SharedObjectFlushStatus.PENDING ) 
				{
					// Add an event handler for netStatus so we can check if the user
					// granted enough disk space to save the shared object. Invoke
					// the onStatus method when the netStatus event is raised.
					obj.addEventListener( NetStatusEvent.NET_STATUS, onStatus );
				} 
				else if ( flushResult == SharedObjectFlushStatus.FLUSHED ) 
				{
					// Saved successfully. Place any code here that you want to
					// execute after the data was successfully saved.
				}
			}
			catch ( e:Error ) 
			{
				// This means the user has the local storage settings to 'Never.'
				// If it is important to save your data, you may want to alert the
				// user here. Also, if you want to make it easy for the user to change
				// his settings, you can open the local storage tab of the Player
				// Settings dialog box with the following code:
				// Security.showSettings( SecurityPanel.LOCAL_STORAGE );.
			}
		}
		
		// Define the onStatus() function to handle the shared object's
		// status event that is raised after the user makes a selection from
		// the prompt that occurs when flush( ) returns "pending."
		public function onStatus( event:NetStatusEvent ):void 
		{
			if ( event.info.code == "SharedObject.Flush.Success" ) 
			{
				// If the event.info.code property is "SharedObject.Flush.Success",
				// it means the user granted access. Place any code here that
				// you want to execute when the user grants access.
			} 
			else if ( event.info.code == "SharedObject.Flush.Failed" ) 
			{
				// If the event.info.code property is "SharedObject.Flush.Failed", it
				// means the user denied access. Place any code here that you
				// want to execute when the user denies access.
			}
			// Remove the event listener now since we only needed to listen once
			event.target.removeEventListener( NetStatusEvent.NET_STATUS, onStatus );
		};
		
		public function onNameOk( e:MouseEvent ):void
		{
			if ( nameMc.nameText.text.length )
			{
				var petArray:Array = GameManager.instance.MainPlayer.petArray;
				var netSocket:NetSocket = GameNetManager.instance.MainNetSocket;
				
				netSocket.writeShort( GameNetEvent.SEND_SET_PET_NAME_SIZE );
				netSocket.writeShort( GameNetEvent.SEND_SET_PET_NAME_ID );
				
				var name:ByteArray = new ByteArray();
				name.writeUTFBytes( nameMc.nameText.text );
				name.length = GameDefine.MAX_NAME;
				
				petArray[ index ].data.Name = name;
				
				netSocket.writeInt( petArray[ index ].ID );
				netSocket.writeBytes( name );
				
				netSocket.Send();
				
				uiMc.nameText.text = name;
				
				nameMc.nameText.text = "";
				
				PetUIHandler.instance.updateData();
			}
		}
		
		public function onSkillBack( e:MouseEvent ):void
		{
			this.visible( true );
			visibleSkill( false );
		}
		
		public function onImgClick( e:MouseEvent ):void
		{
			var d:int = pet.Direction();
			d++;
			
			if ( d == MapDirection.DIRECTCOUNT )
			{
				d = 0;
			}
			
			pet.setDirect( d );
			pet.setAction( GameAction.STAND );
		}
		
		public function show( i:int ):void
		{
			index = i;
			
			if ( uiMc )
			{
				var petArray:Array = GameManager.instance.MainPlayer.petArray;
				
				var data:GameCreatureData = petArray[ index ].data;
				
				uiMc.nameText.text = data.Name;
				uiMc.levelText.text = data.Level.toString();
				uiMc.expText.text = data.EXP.toString();
				uiMc.nextEXPText.text = data.NextEXP.toString();
				
				uiMc.maxHpText.text = data.MAXHP.toString();
				uiMc.hpText.text = data.HP.toString();
				uiMc.attackText.text = data.Strength.toString();
				uiMc.defenceText.text = data.Toughness.toString();
				uiMc.quickText.text = data.Dexterity.toString();
				uiMc.charmText.text = data.Charm.toString();
				
				pet = petArray[ index ];
				pet.setDirect( MapDirection.WEST );
				pet.setAction( GameAction.STAND );
			}

			visible( true );			
		}
		
		public override function update( delay:Number ):void
		{
			super.update( delay );
			
			if ( !uiMc )
			{
				return;
			}
			
			if ( !uiMc.visible )
			{
				return;
			}
			
			if ( pet )
			{
				pet.update( delay );
				
				var textureID:int = pet.ActionTextureID;
				
				if ( !actionBmpData[ textureID ] ) 
				{
					return;
				}
				
				//if ( textureID != GameDefine.INVALIDID )
				//{
					imgSprite.graphics.clear();
					imgSprite.graphics.beginBitmapFill( actionBmpData[ textureID ].bd );
					imgSprite.graphics.drawRect( 0 , 0 , actionBmpData[ textureID ].w , actionBmpData[ textureID ].h );
					imgSprite.graphics.endFill();
					imgSprite.x = actionBmpData[ textureID ].px;
					imgSprite.y = actionBmpData[ textureID ].py;
				//}
			}
		}
		
		public static var instance:PetInfoUIHandler = null;
		public static function Instance():PetInfoUIHandler
		{
			if ( instance == null )
			{
				instance = new PetInfoUIHandler();
			}
			
			return instance;
		}
		
	}
}